package com.yfunc.common.command.handlers;

import java.lang.reflect.Method;
import java.util.Arrays;

import com.yfunc.common.command.Command;
import com.yfunc.common.command.CommandHandler;

public abstract class AbstractCommandHandler implements CommandHandler {

	public abstract Class<?>[] supportedCommands();

	@Override
	public Command execute(Command command) {
		try {
			Method method =  this.getClass().getMethod("on", command.getClass());
			Object returnCommand = method.invoke(this, command);
			return (Command)returnCommand;
		} catch (Exception e) {
			throw new RuntimeException(this.getClass().getName() + " Not Implements Method: when(" + command.getClass() +")");
		}
		
	}

	@Override
	public boolean isSupported(Command command) {
		if( command == null){
			return false;
		}
		for (Class supportedEventClass : supportedCommands()) {
			if(supportedEventClass != null && supportedEventClass.equals(command.getClass())) {
				return true;
			}
		}
		return false;
	}
	
	
	
	@Override
	public boolean equals(Object obj) {
		if(obj != null && obj instanceof AbstractCommandHandler ) {
			AbstractCommandHandler absHandler = (AbstractCommandHandler)obj;
			return Arrays.equals(this.supportedCommands(), absHandler.supportedCommands());
		}
		return false;
	}
	
	@Override
	public int hashCode() {
		int hash = 3377 * 11 ;
		for (Class supportedEventClass : supportedCommands()) {
			hash += supportedEventClass.hashCode();
		}
		return hash;
	}

}
